import functools
import json
from flask import (current_app, Blueprint, g, request, session)
from gitapp.db import get_db
from gitapp import consts
import re
import requests

app = current_app
bp = Blueprint("gitapp", __name__, url_prefix="/gitapp")

@bp.route("/gitcallback", methods=("GET", "POST"))
def gitcallback():
    app.logger.debug("[GITCALLBACK!]" + json.dumps(request.args))

        
    db = get_db()
    name = request.args.get("name", "defaultName")
    queryResult = db.execute("SELECT key, value FROM kv WHERE key = ?", (name,)).fetchone()
    
    if request.method == "GET":
        app.logger.debug("[GITCALLBACK] GET INVOKE!")
        if (queryResult is not None):
            return {"key":queryResult[0],"value":queryResult[1]}
        return "GITCALLBACK"
    else:
        app.logger.debug("[GITCALLBACK] POST INVOKE")
        if (queryResult is not None):
            return "{} exists!".format(queryResult[0])
        else:
            db.execute("INSERT INTO kv (key, value) VALUES (?, ?)", (name, value))
            db.commit()
            return "POST-GITCALLBACK"

@bp.route("/gitcode", methods=("GET","POST"))
def gitcode():
    db = get_db()
    code = request.args.get("code")
    if code is None:
        return "Please transfer code"
    else:
        getInfoParam = consts.getClientInfo()
        getInfoParam["code"] = code
        
        authUrl = consts.getAuthUrl()
        for key,item in getInfoParam.items():
            authUrl = re.compile("\\{%s\\}" % key).sub(item, authUrl)             

        app.logger.debug("After Deal Url:" + authUrl)
        res = requests.post(authUrl)
        app.logger.debug("[Get Response]")
        app.logger.debug(res.text)
        return getInfo
